<template>
  <div class="login-container">
    <div class="login-box" style="width: 50%;margin-left: 250px;">
      <h2 class="login-title">普通管理员登录</h2>

      <div class="form-item">
        <label>账号</label>
        <input type="text" v-model="loginData.account" placeholder="请输入账号">
      </div>

      <div class="form-item">
        <label>密码</label>
        <input type="password" v-model="loginData.password" placeholder="请输入密码">
      </div>

      <button class="login-btn" @click="login">登录</button>
    </div>
    <div class="system-title" style="width: 50%;">
      <h1>靖边县人民政协</h1>
      <h2>智慧政务管理服务系统</h2>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
//调用后台接口完成注册
import { adminLoginService, getAdminInfoService } from '@/api/admin.js'
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'
import { useAdminStore } from '@/stores/admin.js'

const router = useRouter()
const tokenStore = useTokenStore();
const adminStore = useAdminStore()

//定义数据模型
const loginData = ref({
  account: '',
  password: '',
})


//定义表单校验规则
const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ]
}

//登录函数
const login = async () => {
    try {
        // 表单验证 - 匹配后端的正则要求
        if (!/^\S{5,16}$/.test(loginData.value.account)) {
            ElMessage.warning('账号必须是5-16位非空字符')
            return
        }
        if (!/^\S{5,16}$/.test(loginData.value.password)) {
            ElMessage.warning('密码必须是5-16位非空字符')
            return
        }

        //调用接口,完成登录
        let result = await adminLoginService({
            ...loginData.value
        });
       
        //把得到的token存储到pinia中
        tokenStore.setToken(result.data.token)
        //获取管理员详细信息
        const adminInfoResult = await getAdminInfoService()
        console.log("登录拉~管理员详细信息：",adminInfoResult)
        if(adminInfoResult.code === 200) {
            // 检查管理员状态
            if (adminInfoResult.data.status === '已注销') {
                ElMessage.error('该管理员账号已注销，无法登录')
                return
            }
            //存储完整的管理员信息
            adminStore.setAdminInfo(adminInfoResult.data)
        } 
        ElMessage.success(result.msg || '登录成功')
        
        //跳转到首页并刷新页面
        router.push('/layout').then(() => {
            window.location.reload()
        })
    } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.msg || '登录失败，请检查账号密码')
    }
}

onMounted(() => {
});

</script>

<style>
@import '@/assets/css/login.css';

</style>